const boardSize = 4;
let board = [];
let score = 0;

function initializeBoard() {
    const gameBoard = document.getElementById('game-board');
    gameBoard.innerHTML = '';

    for (let i = 0; i < boardSize; i++) {
        board[i] = [];
        for (let j = 0; j < boardSize; j++) {
            const tile = document.createElement('div');
            tile.classList.add('tile');
            gameBoard.appendChild(tile);
            board[i][j] = 0;
        }
    }
    addRandomTile();
    addRandomTile();
    updateBoard();
    updateScore();
}

function addRandomTile() {
    const emptyTiles = [];
    for (let i = 0; i < boardSize; i++) {
        for (let j = 0; j < boardSize; j++) {
            if (board[i][j] === 0) {
                emptyTiles.push({ row: i, col: j });
            }
        }
    }
    if (emptyTiles.length > 0) {
        const randomTile = emptyTiles[Math.floor(Math.random() * emptyTiles.length)];
        board[randomTile.row][randomTile.col] = Math.random() > 0.9 ? 4 : 2;
        updateBoard();
    }
}

function updateBoard() {
    const tiles = document.querySelectorAll('.tile');
    tiles.forEach((tile, index) => {
        const row = Math.floor(index / boardSize);
        const col = index % boardSize;
        tile.textContent = board[row][col] || '';
        tile.classList.remove('tile-2', 'tile-4', 'tile-8', 'tile-16', 'tile-32', 'tile-64', 'tile-128', 'tile-256', 'tile-512', 'tile-1024', 'tile-2048');
        if (board[row][col] !== 0) {
            tile.classList.add(`tile-${board[row][col]}`);
        }
    });
}

function compress(board) {
    let newBoard = [];
    for (let i = 0; i < boardSize; i++) {
        newBoard[i] = [];
        for (let j = 0; j < boardSize; j++) {
            newBoard[i][j] = 0;
        }
    }

    for (let i = 0; i < boardSize; i++) {
        let pos = 0;
        for (let j = 0; j < boardSize; j++) {
            if (board[i][j] !== 0) {
                newBoard[i][pos] = board[i][j];
                pos++;
            }
        }
    }
    return newBoard;
}

function merge(board) {
    for (let i = 0; i < boardSize; i++) {
        for (let j = 0; j < boardSize - 1; j++) {
            if (board[i][j] !== 0 && board[i][j] === board[i][j + 1]) {
                board[i][j] *= 2;
                board[i][j + 1] = 0;
                score += board[i][j];
            }
        }
    }
    return board;
}

function reverse(board) {
    let newBoard = [];
    for (let i = 0; i < boardSize; i++) {
        newBoard[i] = [];
        for (let j = 0; j < boardSize; j++) {
            newBoard[i][j] = board[i][boardSize - 1 - j];
        }
    }
    return newBoard;
}

function transpose(board) {
    let newBoard = [];
    for (let i = 0; i < boardSize; i++) {
        newBoard[i] = [];
        for (let j = 0; j < boardSize; j++) {
            newBoard[i][j] = board[j][i];
        }
    }
    return newBoard;
}

function areBoardsEqual(board1, board2) {
    for (let i = 0; i < boardSize; i++) {
        for (let j = 0; j < boardSize; j++) {
            if (board1[i][j] !== board2[i][j]) {
                return false;
            }
        }
    }
    return true;
}

function moveTiles(direction) {
    let rotatedBoard = JSON.parse(JSON.stringify(board));

    switch (direction) {
        case 'left':
            rotatedBoard = compress(rotatedBoard);
            rotatedBoard = merge(rotatedBoard);
            rotatedBoard = compress(rotatedBoard);
            break;
        case 'right':
            rotatedBoard = reverse(rotatedBoard);
            rotatedBoard = compress(rotatedBoard);
            rotatedBoard = merge(rotatedBoard);
            rotatedBoard = compress(rotatedBoard);
            rotatedBoard = reverse(rotatedBoard);
            break;
        case 'up':
            rotatedBoard = transpose(rotatedBoard);
            rotatedBoard = compress(rotatedBoard);
            rotatedBoard = merge(rotatedBoard);
            rotatedBoard = compress(rotatedBoard);
            rotatedBoard = transpose(rotatedBoard);
            break;
        case 'down':
            rotatedBoard = transpose(rotatedBoard);
            rotatedBoard = reverse(rotatedBoard);
            rotatedBoard = compress(rotatedBoard);
            rotatedBoard = merge(rotatedBoard);
            rotatedBoard = compress(rotatedBoard);
            rotatedBoard = reverse(rotatedBoard);
            rotatedBoard = transpose(rotatedBoard);
            break;
    }

    if (!areBoardsEqual(rotatedBoard, board)) {
        board = rotatedBoard;
        addRandomTile();
        updateBoard();
        updateScore();
        checkGameOver();
    }
}

function updateScore() {
    document.getElementById('score-value').textContent = score;
}

function checkGameOver() {
    if (isGameOver()) {
        alert("Game Over! Your score: " + score);
        if (confirm("Restart game?")) {
            initializeBoard();
        }
    }
}

function isGameOver() {
    for (let i = 0; i < boardSize; i++) {
        for (let j = 0; j < boardSize; j++) {
            if (board[i][j] === 0) {
                return false;
            }
        }
    }

    for (let i = 0; i < boardSize; i++) {
        for (let j = 0; j < boardSize - 1; j++) {
            if (board[i][j] === board[i][j + 1]) {
                return false;
            }
        }
    }

    for (let j = 0; j < boardSize; j++) {
        for (let i = 0; i < boardSize - 1; i++) {
            if (board[i][j] === board[i + 1][j]) {
                return false;
            }
        }
    }

    return true;
}

// 监听键盘事件
document.addEventListener('keydown', (event) => {
    switch (event.key) {
        case 'ArrowUp':
            moveTiles('up');
            break;
        case 'ArrowDown':
            moveTiles('down');
            break;
        case 'ArrowLeft':
            moveTiles('left');
            break;
        case 'ArrowRight':
            moveTiles('right');
            break;
    }
});

// 监听触摸事件
let startX, startY;

document.getElementById('game-board').addEventListener('touchstart', (event) => {
    const touch = event.touches[0];
    startX = touch.clientX;
    startY = touch.clientY;
});

document.getElementById('game-board').addEventListener('touchend', (event) => {
    const touch = event.changedTouches[0];
    const endX = touch.clientX;
    const endY = touch.clientY;

    const deltaX = endX - startX;
    const deltaY = endY - startY;

    const absX = Math.abs(deltaX);
    const absY = Math.abs(deltaY);

    if (absX > absY && absX > 10) { // 水平滑动
        if (deltaX > 0) {
            moveTiles('right');
        } else {
            moveTiles('left');
        }
    } else if (absY > absX && absY > 10) { // 垂直滑动
        if (deltaY > 0) {
            moveTiles('down');
        } else {
            moveTiles('up');
        }
    }
});

document.getElementById('restart-button').addEventListener('click', () => {
    score = 0;
    updateScore();
    initializeBoard();
});
document.addEventListener('touchmove', function(event) {
    event.preventDefault(); // 阻止默认的滚动行为
}, { passive: false });

// 其他游戏逻辑代码...
initializeBoard();